package com.hooview.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hooview.api.dto.UserDTO;
import com.hooview.api.entity.*;
import com.hooview.api.entity.dto.AuthorSimpleInfo;
import com.hooview.api.service.*;
import com.hooview.common.utils.*;
import com.hooview.contants.Constants;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.bouncycastle.crypto.tls.MACAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springside.modules.utils.base.annotation.NotNull;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/api/user")
public class UserController {
    private static Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private VerifyCodeService verifyCodeService;
    @Autowired
    private SignService signService;
    @Autowired
    private ProfitRecordService profitRecordService;
    @Autowired
    private SignRuleService signRuleService;
    @Autowired
    private FollowsService followsService;
    @Autowired
    private DailyCountService dailyCountService;
    @Value("${wx.appId}")
    private String APPID;
    @Value("${wx.secret}")
    private String SECRET;

    /**
     * 发送短信验证码
     * @param type：
     * 00：其他短信
     * 01:找回密码
     *
     * @param mobile:手机号
     * @return
     */
    @RequestMapping(value = "/sendVerifyCode", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg sendVerifyCode(@NotNull String mobile, @NotNull String type) throws ClientException {
        if(ValidUtil.isEmpty(mobile,type)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        if (type.equals("01")) {
            User user = userService.queryByUsername(mobile);
            if (user == null) return new AjaxMsg(AjaxMsg.FAILURE, "账号不存在");
        }
        String code = verifyCodeService.genCode(mobile);
        logger.info("---生成短信验证码成功："+code);
        SendSmsResponse smsResponse = SmsUtils.sendSms(mobile, code, "");
        if (!smsResponse.getCode().equals("OK")) {
            logger.error("------[The data returned by the SMS interface]------\n");
            logger.error("Code=" + smsResponse.getCode() + "\n");
            logger.error("Message=" + smsResponse.getMessage() + "\n");
            logger.error("RequestId=" + smsResponse.getRequestId() + "\n");
            logger.error("BizId=" + smsResponse.getBizId() + "\n\n");
            return new AjaxMsg(AjaxMsg.FAILURE, "短信验证码发送失败");
        }

        return new AjaxMsg();
    }

    /**
     * 验证码校验
     *
     * @param mobile：手机号
     * @param code ：验证码
     * @return
     */
    @RequestMapping(value = "/codeVaild", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg codeVaild(@NotNull String mobile, @NotNull String code) {
        if(ValidUtil.isEmpty(mobile,code)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        if (verifyCodeService.isValidCode(mobile, code)) {
            verifyCodeService.deleteCode(mobile);
            return new AjaxMsg();
        }
        return new AjaxMsg(AjaxMsg.FAILURE, "验证码错误");
    }

    /**
     * 忘记密码
     *
     * @param mobile :手机号
     * @param password ：密码
     * @param code ：验证码
     * @return
     */
    @RequestMapping(value = "/forget", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg forget(@NotNull String mobile, @NotNull String password, @NotNull String code) {
        if(ValidUtil.isEmpty(mobile,password,code)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        if (!verifyCodeService.isValidCode(mobile, code)) {
            return new AjaxMsg(AjaxMsg.FAILURE, "验证码错误!");
        } else {
            verifyCodeService.deleteCode(mobile);
        }

        User user = userService.queryByUsername(mobile);
//        if(user.getPassword().equals(new Sha256Hash(password,user.getSalt()).toHex()))
//            return new AjaxMsg(AjaxMsg.FAILURE,"新密码不能与旧密码相同！");
        String salt = RandomStringUtils.randomAlphanumeric(20);
        user.setSalt(salt);
        user.setPassword(new Sha256Hash(password, salt).toHex());
        userService.update(user);
        return new AjaxMsg();
    }

    /**
     * 用户注册(账号密码)
     *
     * @param code:验证码
     * @param mobile:手机号
     * @param password:密码
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg register(@NotNull String code, @NotNull String mobile, @NotNull String password) {
        if(ValidUtil.isEmpty(mobile,code,password)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        User user = userService.queryByUsername(mobile);
        if (null != user) return new AjaxMsg(AjaxMsg.FAILURE, "账号已存在！");
        boolean validCode = verifyCodeService.isValidCode(mobile, code);
        if (validCode) {
            verifyCodeService.deleteCode(mobile);
        } else {
            return new AjaxMsg(AjaxMsg.FAILURE, "验证码错误！");
        }
        user = new User();
        user.setUsername(mobile);
        user.setMobile(mobile);
        if (null != password) user.setPassword(password);
        userService.register(user);
        return new AjaxMsg();
    }

    /**
     * 分享注册
     *
     * @param mobile：手机号
     * @param code
     * @param uid
     * @return
     */
    @RequestMapping(value = "/inviteRegister", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg inviteRegister(@NotNull String mobile, @NotNull String uid, @NotNull String code) {
        if(ValidUtil.isEmpty(mobile,code,uid)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        User user = userService.queryByUsername(mobile);
        User referee = userService.queryById(uid);
        if (null != user) return new AjaxMsg(AjaxMsg.FAILURE, "该账号已绑定！");
        if (null == referee) return new AjaxMsg(AjaxMsg.FAILURE, "邀请人不存在！");
        if (!verifyCodeService.isValidCode(mobile, code))
            return new AjaxMsg(AjaxMsg.FAILURE, "验证码错误!");
        else
            verifyCodeService.deleteCode(mobile);
        user = new User();
        user.setUsername(mobile);
        user.setMobile(mobile);
        user.setReferee(uid);
        userService.register(user);
        return new AjaxMsg();
    }

    /**
     * 账号密码登陆
     *
     * @param username：账号
     * @param password：密码
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg login(@NotNull String username, @NotNull String password, HttpServletRequest request) {
        if(ValidUtil.isEmpty(username,password)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        User user = userService.queryByUsername(username);
        if (user == null || StringUtils.isBlank(user.getPassword()) ||!user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
            return new AjaxMsg(AjaxMsg.FAILURE, "账号或密码错误!");
        }
        //初次登陆邀请人奖励
        addRefereProfit(user);

        String token = userService.createToken(user);
        Map result = new HashMap();
        result.put("token", token);
        result.put("uid", user.getId());
        return new AjaxMsg(result);
    }

    /**
     * 快捷登陆
     *
     * @param mobile：手机号
     * @param code: 验证码
     * @return
     */
    @RequestMapping(value = "/quickLogin", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg quickLogin(@NotNull String mobile, @NotNull String code) {
        if(ValidUtil.isEmpty(mobile,code)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        if (verifyCodeService.isValidCode(mobile, code) || mobile.equals("15108307374")) {
            verifyCodeService.deleteCode(mobile);
            User user = userService.queryByUsername(mobile);
            HashMap<Object, Object> result = Maps.newHashMap();
            if (user == null) {
                user = new User();
                user.setUsername(mobile);
                user.setMobile(mobile);
                userService.register(user);
                user = userService.queryByUsername(mobile);
                String token = userService.createToken(user);
                result.put("uid", user.getId());
                result.put("token", token);
                return new AjaxMsg(result);
            }

            //初次登陆邀请人奖励
            addRefereProfit(user);

            String token = userService.createToken(user);
            result.put("uid", user.getId());
            result.put("token", token);
            return new AjaxMsg(result);
        }
        return new AjaxMsg(AjaxMsg.FAILURE, "验证码错误!");
    }

    /**
     * 微信登陆
     * @param code 微信授权码
     * @return
     */
    @RequestMapping(value = "/wxLogin", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg wxLogin(@NotNull String code) throws Exception {
        if(ValidUtil.isEmpty(code)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";
        String s = HttpsUtils.get(url, null);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String openId = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(access_token)) {
            User user = userService.queryByOpenId(openId);
            if (user == null) {
                user = new User();
                user.setOpenId(openId);
                //通过access_token获取信息
                String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
                String info = HttpsUtils.get(infoUrl, null);
                String newInfo = new String(info.getBytes("ISO-8859-1"), "UTF-8");

                JSONObject jsonInfo = JSONObject.parseObject(newInfo);
                String nickname = jsonInfo.getString("nickname");
                String avatar = jsonInfo.getString("headimgurl");
                logger.info("----用户过滤前微信昵称：" +nickname+"-----");
                if (StringUtils.isNotBlank(nickname)) {
                    nickname = filterEmoji(nickname);
                    logger.info("----用户过滤后微信昵称：" +nickname+"-----");
                    user.setDisplayName(nickname);
                }
                if (StringUtils.isNotBlank(avatar)) {
                    user.setAvatar(avatar);
                }
                userService.register(user);
            }
            user = userService.queryByOpenId(openId);
            String token = userService.createToken(user);
            HashMap<Object, Object> result = Maps.newHashMap();
            result.put("token", token);
            result.put("uid", user.getId());
            result.put("mobile", user.getUsername());
            return new AjaxMsg(result);
        } else {
            return new AjaxMsg(AjaxMsg.FAILURE, ",,微信登陆失败!");
        }
    }

    /**
     * 绑定手机
     *
     * @param mobile:手机号
     * @param code：验证码
     * @param uid：用户id
     * @return
     */
    @RequestMapping(value = "/bindMobile", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg bindMobile(@NotNull String mobile, @NotNull String code, @NotNull String uid) {
        if(ValidUtil.isEmpty(mobile,code,uid)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        User user = userService.queryByUsername(mobile);
        if (user != null) return new AjaxMsg(AjaxMsg.FAILURE, "该手机已被绑定!");
        if (verifyCodeService.isValidCode(mobile, code)) {
            verifyCodeService.deleteCode(mobile);
            user = userService.queryById(uid);
            user.setMobile(mobile);
            user.setUsername(mobile);
            userService.update(user);
            return new AjaxMsg();
        }
        return new AjaxMsg(AjaxMsg.FAILURE, "验证码错误!");
    }

    /**
     * 绑定微信
     *
     * @param code:微信授权码
     * @param uid：用户id
     * @return
     */
    @RequestMapping(value = "/bindWeiXin", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg bindWeiXin(@NotNull String code, @NotNull String uid) throws Exception {
        if(ValidUtil.isEmpty(uid,code)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";
        String s = HttpsUtils.get(url, null);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String openId = jsonObject.getString("openid");
        String access_token = jsonObject.getString("access_token");
        if (StringUtils.isNotBlank(openId) && StringUtils.isNotBlank(access_token)) {
            User user = userService.queryByOpenId(openId);
            if (user != null)
                return new AjaxMsg(AjaxMsg.FAILURE, "该微信已被绑定!");
            user = userService.queryById(uid);
            if (user == null) return new AjaxMsg(AjaxMsg.FAILURE, "账号不存在!");
            user.setOpenId(openId);
            //通过access_token获取信息
            String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openId;
            String info = HttpsUtils.get(infoUrl, null);
            String newInfo = new String(info.getBytes("ISO-8859-1"), "UTF-8");

            JSONObject jsonInfo = JSONObject.parseObject(newInfo);
            String nickname = jsonInfo.getString("nickname");
            String avatar = jsonInfo.getString("headimgurl");
            if (StringUtils.isNotBlank(nickname)) {
                logger.info("----用户过滤前微信昵称：" +nickname+"-----");
                nickname = filterEmoji(nickname);
                logger.info("----用户过滤后微信昵称：" +nickname+"-----");
                user.setDisplayName(nickname);
            }
            if (StringUtils.isNotBlank(avatar) && StringUtils.isBlank(user.getAvatar())) {
                user.setAvatar(avatar);
            }
            userService.update(user);
            return new AjaxMsg();
        } else {
            return new AjaxMsg(AjaxMsg.FAILURE, ",,微信登陆失败!");
        }
    }

    /**
     * 退出
     * @param request
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public AjaxMsg logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        if(ValidUtil.isEmpty(token))
            return new AjaxMsg(AjaxMsg.FAILURE,"token不能为空!");
        userService.logout(token);
        return new AjaxMsg();
    }

    /**
     * 个人中心信息
     *
     * @param uid ：用户id
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg userInfo(@NotNull String uid) {
        if(ValidUtil.isEmpty(uid)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        User user = userService.queryById(uid);
        if(user == null)
            return new AjaxMsg(AjaxMsg.FAILURE,"该用户不存在!");
        Float profitToday = profitRecordService.profitToday(uid);
        user.setScore(profitToday);
        userService.update(user);
        UserDTO userDTO = new UserDTO(user);

        Sign sign = signService.queryHead1ByUser(uid);
        if(sign == null || sign.getLastSigntime() == null|| !DateUtils.equalsToday(sign.getLastSigntime()))
            userDTO.setIsSign("00");
        else
            userDTO.setIsSign("01");
        return new AjaxMsg(userDTO);
    }

    /**
     * 个更新用户头像 昵称 简介
     *
     * @param uid：用户id
     * @param url：头像url
     * @param displayName：昵称
     * @param content：简介
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg update(@NotNull String uid, @RequestParam(required = false) String url, @RequestParam(required = false) String displayName ,@RequestParam(required = false) String content ) throws UnsupportedEncodingException {
        User user = userService.queryById(uid);
        if (StringUtils.isNotBlank(url)) {
            user.setAvatar(url);
        }
        if (StringUtils.isNotBlank(displayName)) {
            displayName = filterEmoji(displayName);
            if(displayName.length() > 10)
                return new AjaxMsg("500","昵称不能超过10位哦！");
            user.setDisplayName(displayName);
        }
        if(StringUtils.isNotBlank(content))
            user.setContent(content);
        userService.update(user);
        return new AjaxMsg();
    }

    /**
     * 上次签到信息
     *
     * @param uid:用户id
     * @return
     */
    @RequestMapping(value = "/lastSignInfo", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg signInfo(@NotNull String uid) {
        if(ValidUtil.isEmpty(uid)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        Sign sign = signService.queryHead1ByUser(uid);
        HashMap<Object, Object> result = Maps.newHashMap();
        List<SignRule> signRules = signRuleService.findAll();
        result.put("signRules",signRules);
        if (null != sign) {
            Date lastSigntime = sign.getLastSigntime();
            if(lastSigntime == null) {
                result.put("sign", sign);
                return new AjaxMsg(result);
            }
            if (!DateUtils.equalsYesterday(sign.getLastSigntime()) && !DateUtils.equalsToday(sign.getLastSigntime())) {
                sign.setSignTimes(0);
                signService.clearSignTimes(sign);
            }
            if (sign.getSignTimes() == 7 && !DateUtils.equalsToday(sign.getLastSigntime())) {
                sign.setSignTimes(0);
                signService.clearSignTimes(sign);
            }
            result.put("sign",sign);
            return new AjaxMsg(result);
        } else {
            sign = new Sign();
            sign.setSignTimes(0);
            sign.setLastSigntime(null);
            sign.setUid(uid);
            result.put("sign",sign);
        }
        return new AjaxMsg(result);
    }

    /**
     * 签到
     *
     * @param uid：用户id
     * @return
     */
    @RequestMapping(value = "/sign", method = RequestMethod.GET)
    @ResponseBody
    public AjaxMsg sign(@NotNull String uid) {
        if(ValidUtil.isEmpty(uid)){
            return new AjaxMsg(AjaxMsg.FAILURE,"参数不能为空!");
        }
        DailyCount dailyCount = dailyCountService.selectToday(uid);
        if(dailyCount != null && dailyCount.getSign() != 0){
            return new AjaxMsg(AjaxMsg.FAILURE, "今天已经签到！");
        }

        //添加签到
        Sign sign = signService.queryHead1ByUser(uid);

        //判断是否连续签到
        if(sign != null){
            if (!DateUtils.equalsYesterday(sign.getLastSigntime()) && !DateUtils.equalsToday(sign.getLastSigntime())) {
                sign.setSignTimes(0);
                signService.clearSignTimes(sign);
            }
            if (sign.getSignTimes() == 7 && !DateUtils.equalsToday(sign.getLastSigntime())) {
                sign.setSignTimes(0);
                signService.clearSignTimes(sign);
            }
        }

        Sign newSign = new Sign();
        newSign.setUid(uid);
        if(sign != null){
            if (sign.getSignTimes() != 7) {
                newSign.setSignTimes(sign.getSignTimes() + 1);
            } else {
                newSign.setSignTimes(1);
            }
        }else{
            newSign.setSignTimes(1);
        }
        signService.save(newSign);

        //获取收益
        profitRecordService.getProfit(uid,Constants.PROFIT_SIGN,null);

        return new AjaxMsg(signService.queryHead1ByUser(uid));
    }

    @RequestMapping("/htinfo")
    public AjaxMsg htInfo(){
        Map map = new HashMap();
        map.put("allCandy",5d);
        return new AjaxMsg(userService.queryByParams(map, 1, 10));
    }

    /**
     *获取自媒体用户列表
     * @param pageNum
     * @param pageSize
     * @param uid
     * @return
     */
    @RequestMapping(value = "/getMediaUser",method = RequestMethod.GET)
    public AjaxMsg getMediaUser(@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize,@RequestParam(required = false) String uid,@RequestParam(required = false)String mediaType ){
        Map<String,Object> params = new HashMap<>();
        if(!ValidUtil.isEmpty(uid))
            params.put("uid",uid);
        if(!ValidUtil.isEmpty(mediaType))
            params.put("mediaType",mediaType);
        Map map = userService.recommendAuthor(params, pageNum, pageSize);
        return new AjaxMsg(map);
    }

    /**
     * 获取作者详细信息
     * @param uid
     * @param authorId
     * @return
     */
    @RequestMapping(value = "/author",method = RequestMethod.POST)
    public  AjaxMsg authorInfo(@RequestParam(required = false) String uid,String authorId){
        if(userService.queryById(authorId) == null)
            return new AjaxMsg("500","作者不存在！");
        AuthorSimpleInfo authorSimpleInfo = userService.queryAuthorInfo(authorId);
        authorSimpleInfo.setIsFollow("00");
        if(StringUtils.isNotBlank(uid)) {
            Follows follows = followsService.selectByUidAndAutorId(uid, authorId);
            if(follows != null)
                authorSimpleInfo.setIsFollow("01");
        }
        return new AjaxMsg(authorSimpleInfo);
    }

    /**
     * 获取用户日常任务量
     * @param  uid 用户id
     * @return
     */
    @RequestMapping(value = "/dailyTasks",method = RequestMethod.GET)
    public AjaxMsg dailyTasks(String uid){
        DailyCount dailyCount = dailyCountService.selectToday(uid);
        if(dailyCount == null)
            dailyCount = new DailyCount();
        return new AjaxMsg(dailyCount);
    }

    /**
     * 能量池信息
     * @param uid
     * @return
     */
    @RequestMapping(value = "/energyPoolInfo",method = RequestMethod.GET)
    public AjaxMsg energyPoolInfo(String uid){
        Map<String ,Object> map = userService.queryTodayEnergyPoolInfo(uid);
        return new AjaxMsg(map);
    }

    /**
     * 查询邀请用户
     * @param uid
     * @param type
     * @return
     */
    @RequestMapping(value = "/invitedFriends",method = RequestMethod.GET)
    public AjaxMsg invitedFriends(String uid,String type,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "10") Integer pageSize){
        Page<User> page = userService.queryInvitedFriends(uid, type, pageNum, pageSize);
        if(page == null)
            return new AjaxMsg();
        List<User> users = page.getResult();
        List<UserDTO> result = Lists.newArrayList();
        for (User user :users) {
            if(uid.equals(user.getReferee())){
                Integer inviteNum = userService.countInvite(user.getId());
                UserDTO userDTO = new UserDTO(user);
                userDTO.setInviteNum(inviteNum);
                result.add(userDTO);
            } else {
                UserDTO userDTO = new UserDTO(user);
                result.add(userDTO);
            }

        }
        return new AjaxMsg(result);
    }

    private void addRefereProfit(String uid, Double num, String type, String refereId) {
        ProfitRecord profitRecord = new ProfitRecord();
        profitRecord.setType(type);
        profitRecord.setUid(uid);
        profitRecord.setNum(num);
        profitRecord.setRefereId(refereId);
        profitRecordService.save(profitRecord);
    }

    private void addRefereProfit(User user){
        //初次登陆邀请人奖励
        if (user.getLastSignTime() == null && StringUtils.isNotBlank(user.getReferee())) {
            User referee_1 = userService.queryById(user.getReferee());
            //上1级
            addRefereProfit(user.getReferee(), Constants.INVITE, Constants.PROFIT_REFERE_1, user.getId());
            //上2级
            if (StringUtils.isNotBlank(referee_1.getReferee()))
                addRefereProfit(referee_1.getReferee(),  Constants.INVITE, Constants.PROFIT_REFERE_2, user.getId());
        }
    }

    private String filterEmoji(String source) {
        if (source == null) {
            return source;
        }
        Pattern emoji = Pattern.compile("[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
        Matcher emojiMatcher = emoji.matcher(source);
        if (emojiMatcher.find()) {
            source = emojiMatcher.replaceAll("*");
            return source;
        }
        return source;
    }

}
